package com.lmf.service;

import com.lmf.Dao.UserDao;
import com.lmf.config.AuthServiceClient;
import com.lmf.entity.Jwt;
import com.lmf.entity.User;
import com.lmf.tool.EPasswordUtil;
import com.lmf.tool.TokenDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    AuthServiceClient authServiceClient;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    public User insertUser(String username,String password){
        User u=new User();
        u.setPassword(EPasswordUtil.MdPassword(password));
        u.setUsername(username);
        return userDao.save(u);
    }

    public TokenDTO login(String username, String password){
        User user=userDao.findByUsername(username);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
        if(!EPasswordUtil.matches(password,user.getPassword())){
            throw new RuntimeException("密码不对");
        }
        //dXNlci1zZXJ2aWNlOjEyMzQ1Ng== 是 lmf:123456的 base64编码
        Jwt jwt=authServiceClient.getToken("Basic bG1mOjEyMzQ1Ng==", "password", username, password);
        if(jwt==null){
            throw new RuntimeException("用户Token有问题");
        }
        TokenDTO tokenDTO=new TokenDTO();
        tokenDTO.setUser(user);
        tokenDTO.setJwt(jwt);
        return tokenDTO;
    }



}
